package com.alex.common.persistent;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.alex.common.security.domain.User;

@Repository
public class UserDao extends BaseDao {

	private UserDao() {
	}

	private static final UserDao me = new UserDao();

	public static UserDao getInstance() {
		return me;
	}

	private static final String FIND = "from " + User.class.getName()
			+ " tb where tb.username = ? ";

	public User find(final String username) {
		return dao(new Run<User>() {
			@Override
			protected User run(EntityManager em) {
				Query query = em.createQuery(FIND);
				query.setParameter(1, username);
				List<?> list = query.getResultList();
				if (list.size() == 0) {
					return null;
				}
				return (User) list.get(0);
			}
		}, true);

	}

	public void save(final User po) {
		dao(new Run<Boolean>() {
			protected Boolean run(EntityManager em) {
				po.setUpdateTime(new Date());
				if (po.getId() != null && po.getId() > 0) {
					em.merge(po);
				} else {
					po.setId(null);
					em.persist(po);
				}
				return true;
			}
		}, false);
	}
}